import React, { useState } from 'react';
import { message, Alert } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { ProFormCheckbox, ProFormText, LoginForm } from '@ant-design/pro-components';
import logo from '@/assets/logo.svg';
import {AmisResp, LoginParams, LoginResp} from "@/types/types.ts";
import useApi from "@/hooks/useApi.tsx";
import {useNavigate} from "react-router-dom";

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const {login} = useApi();
  const navigate = useNavigate();

  const [loginResult, setLoginResult] = useState<AmisResp<LoginResp>>({status: 0, msg: '', data: null});

  async function handleSubmit(values: LoginParams) {
    try {
      const result = await login(values);
      if (result) {
        // 保存token
        localStorage.setItem('token', result.data?.tokenValue ?? '');
        message.success('登录成功！');
        const urlParams = new URL(window.location.href).searchParams;
        navigate(urlParams.get('redirect') ?? '/');
        return;
      }
      else {
        setLoginResult(result);
      }
    } catch (error) {
      message.error('登录失败，请重试！');
    }
  }
  return (
    <div>
      <LoginForm
        title="萌心芽铺货系统"
        logo={<img alt="logo" src={logo} />}
        subTitle="为了时间自由，为了财富自由"
        onFinish={async (values) => {
          await handleSubmit(values as LoginParams);
        }}
      >
        {loginResult.status !== 0 && (
          <LoginMessage
            content={loginResult.msg}
          />
        )}
        <ProFormText
          name="username"
          fieldProps={{
            size: 'large',
            prefix: <UserOutlined className={'prefixIcon'} />,
          }}
          placeholder={'请输入用户名'}
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined className={'prefixIcon'} />,
          }}
          placeholder={'请输入密码'}
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        />
        <div
          style={{
            marginBottom: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a
            style={{
              float: 'right',
            }}
          >
            忘记密码
          </a>
        </div>
      </LoginForm>
    </div>
  );
};

export default Login;
